// 公共方法(基础) 'const $app = getApp()'  '$app.$common_base'
let ceshi_i = 0
export default{
  // ===================== 初始化项目 =====================
  initProject () {
    const $app = getApp()
    $app.menuCurrent = null // 当前所在的一级菜单
    $app.userInfo = {} // 用户信息
    $app.menuAuth = [] // 菜单权限
    $app.Auth = {} // 页面权限
  },
  // ===================== 获取菜单权限 =====================
  getMenuAuth (roleid) {
    const $app = getApp()
    if (!roleid) {
      $app.$common.message('数据不全，请重试', 'error')
      $app.$common.closeLoading() // 关闭加载
      return
    }
    $app.$common.openLoading() // 开启加载
    $app.$api.login.getPermissionArray({ roleid: roleid }).then(({ data }) => {
      console.log('api-菜单权限', data)
      $app.menuAuth = data || []
      // 配置一级菜单权限
      if ($app.menuAuth.length) {
        for (const k in $app.menuData) {
          let b = $app.menuData[k]
          if (b.Auth) b.show = $app.menuAuth.includes(b.Auth)
        }
      }
      $app.$common.closeLoading() // 关闭加载
      wx.reLaunch({ url: '/pages/home/home' })
      this.getSubscribeMsgAuth() // 获取消息订阅权限
      this.getListData_depart() // 获取列表数据: 部门
    }).catch((res) => {})
  },
  // ===================== 获取列表数据: 部门 =====================
  getListData_depart (callback) {
    const $app = getApp()
    if ($app.listData.depart.length) return
    $app.$api.login.returnDepart({
      departid: $app.userInfo.departid
    }).then(({ data }) => {
      console.log('api-列表数据: 部门', data)
      const newData = data || []
      $app.listData.depart = newData
      callback && typeof callback === 'function' && callback(newData) // 执行回调函数
    }).catch((res) => {})
  },
  // ===================== 获取消息订阅权限 =====================
  getSubscribeMsgAuth () {
    const $app = getApp()
    wx.getSetting({ // 获取用户的当前设置
      withSubscriptions: true,
      success: (res) => {
        const set = res.subscriptionsSetting
        let tmplIds = []
        if (set.mainSwitch) {
          $app.tmplIds.forEach(b => {
            const tmplId = set.itemSettings && set.itemSettings[b] ? set.itemSettings[b] : null
            if (!tmplId || tmplId !== 'accept') tmplIds.push(b)
          })
        }
        if (tmplIds.length) {
          wx.showModal({
            title: '提示',
            content:'请授权开通服务通知',
            showCancel: true,
            success: (res1) => {
              if (res1.confirm) {
                // 调起客户端小程序订阅消息界面
                wx.requestSubscribeMessage({
                  tmplIds: tmplIds,
                  success: (res2) => {
                    console.log('wx-订阅消息 成功', res2)
                  },
                  fail: (res2) => {
                    console.log('wx-订阅消息 失败', res2)
                    $app.$common.message('订阅失败，无法接收消息！', 'error')
                  }
                })
              } else {
                $app.$common.message('注意：未开启消息订阅，无法接收消息！', 'error')
              }
            }
          })
        }
      },
      fail: (res) => {
        console.log('wx-获取用户的当前设置 失败', res)
        $app.$common.message('订阅失败，无法接收消息！', 'error')
      }
    })
  },
  // ===================== 获取页面权限 =====================
  getAuth (path) {
    return new Promise((resolve) => {
      const $app = getApp()
      const menu = path.substring(path.lastIndexOf('/') + 1) // 当前页
      let AuthData = {} // 当前页具体权限
      if ($app.Auth[menu]) {
        AuthData = $app.Auth[menu]
        resolve(AuthData)
        return
      }
      const arr = $app.menuData_work[menu].Auth // 当前页权限数组
      const isMutil = Boolean(arr.length > 1)
      for (const i in arr) {
        const b = arr[i]
        let obj = $app.AuthData[b] || null
        if (!obj) continue
        for (const k in obj) {
          AuthData[(isMutil ? `${b}_` : '') + k] = obj[k]
        }
      }
      if (JSON.stringify(AuthData) === '{}') {
        $app.Auth[menu] = AuthData // 储存在公共变量中
        resolve(AuthData)
        return
      }
      $app.$api.login.getPagePermissionArray({
        roleid: $app.userInfo.roleid,
        pageArray: arr,
        '*': true,
        '/': true
      }).then(({ data }) => {
        console.log(`axios-权限-${menu}0`, data)
        for (const k in AuthData) {
          AuthData[k] = (data || []).includes(AuthData[k])
        }
        console.log(`axios-权限-${menu}`, AuthData)
        $app.Auth[menu] = AuthData // 储存在公共变量中
        resolve(AuthData)
      }).catch((res, type) => {
        $app.Auth[menu] = {} // 储存在公共变量中
        resolve(AuthData)
      })
    })
  },
  // ===================== 获取未读消息数量 =====================
  getNoReadMsgNum (callback) {
    const $app = getApp()
    $app.$api.systemmessage.getCount({
      userId: $app.userInfo.id,
      roleId: $app.userInfo.roleid
    }).then(({ data }) => {
      let obj = data || {}
      const arr = ['sum', 'spsum', 'dqsum', 'jfsum', 'xjsum']
      for (const i in arr) {
        const k = arr[i]
        obj[k] = obj[k] || 0
        if (obj[k] === $app.noReadMsgNum[k]) continue
        $app.noReadMsgNum[k] = obj[k]
      }
      if (callback) { // 执行回调函数
        callback && typeof callback === 'function' && callback(obj)
      } else { // 再次获取
        setTimeout(() => { this.getNoReadMsgNum(false) }, 5000)
      }
    })
  },
  getNoReadMsgNumCeshi (callback) { // 测试 模拟数据
    const $app = getApp()
    const arr0 = ['spsum', 'dqsum', 'jfsum', 'xjsum']
    let data = Object.assign({}, $app.noReadMsgNum)
    data.sum = 0
    arr0.forEach((k, n) => {
      data[k] = ceshi_i%4 === n ? data[k] + 1 : data[k]
      data.sum += data[k]
    })
    let obj = data || {}
    const arr = ['sum', 'spsum', 'dqsum', 'jfsum', 'xjsum']
    for (const i in arr) {
      const k = arr[i]
      obj[k] = obj[k] || 0
      if (obj[k] === $app.noReadMsgNum[k]) continue
      $app.noReadMsgNum[k] = obj[k]
    }
    if (callback) { // 执行回调函数
      callback && typeof callback === 'function' && callback(obj)
    } else { // 再次获取
      ceshi_i++
      setTimeout(() => { this.getNoReadMsgNumCeshi(false) }, 5000)
    }
  }
}